#include "ble.h"
#include "usart.h"

#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"
#include "stdio.h"
#include "bd_gps.h"
#include "gl_parser.h"


enum BLE_STATUS_ENUM ble_status = BLE_CONNECTING;
extern struct BD_GPS_STRUCT bd_gps_s;
struct RC_VALUE_STRUCT rc_value_s;

SemaphoreHandle_t xSemaphore;

PARSE_STRUCT parse_uart;
uint8_t is_recv = 0;

void receive_uart_data(uint8_t *receive_buffer, uint16_t receive_len)
{
    parse_data(&parse_uart, receive_buffer, receive_len);
}

void send_uart_data(uint8_t *send_buffer, uint16_t send_len)
{
    uart_transmit1_buffer(send_buffer, send_len);
}

void recv_uart_farme(void *arg)
{
    static BaseType_t xHigherPriorityTaskWoken;
    xSemaphoreGiveFromISR(xSemaphore, &xHigherPriorityTaskWoken);
}


void parse_loop(void)
{
    if (parse_uart.frame_s.MasterCmd == MASTER_CMD_STATUS)
    {
        //printf("recv frame \r\n");
        parse_status_frame(&parse_uart);
    }
//    else if (parse_uart.frame_s.MasterCmd == MASTER_CMD_FLASH)
//    {
//        parse_flash_frame(&parse_uart);
//    }
}

void StartBleTask(void const *argument)
{
    xSemaphore = xSemaphoreCreateBinary();
    
    parse_struct_init(&parse_uart);
    parse_set_rec_callback(&parse_uart, recv_uart_farme);
    parse_set_send_fun(&parse_uart, send_uart_data);
    
    ble_init();
    
    while(1)
    {
        if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE)
        {
            parse_loop();
        }
    }
}

void send_bd_gps_status(void)
{
    
    FRAME_STRUCT frame_s;

    frame_s.Version = PROTOCOL_VERSION;
    frame_s.FrameDataLen = sizeof(struct BD_GPS_STRUCT);
    frame_s.MasterCmd = MASTER_CMD_STATUS;
    frame_s.SlaveCmd = SLAVE_CMD_STATUS_GPS;
    frame_s.frame_data = (uint8_t *)&bd_gps_s;
    frame_s.send_frame_fun = ble_send;
    creat_send_cmd(&frame_s);
}

void send_rc_value(void)
{
    
    FRAME_STRUCT frame_s;

    frame_s.Version = PROTOCOL_VERSION;
    frame_s.FrameDataLen = sizeof(struct RC_VALUE_STRUCT);
    frame_s.MasterCmd = MASTER_CMD_STATUS;
    frame_s.SlaveCmd = SLAVE_CMD_RC_VALUE;
    frame_s.frame_data = (uint8_t *)&rc_value_s;
    frame_s.send_frame_fun = ble_send;
    creat_send_cmd(&frame_s);
}

void ble_send(uint8_t *data,uint16_t length)
{
    if(ble_status == BLE_CONNECTED)
    {
        uart_transmit1_buffer(data,length);
    }
}